const path = require('path');
const fs = require('fs');
require('dotenv').config();

// 导入Software模型
const Software = require('../models/software');

// 获取所有软件列表
exports.getAllSoftware = async (req, res) => {
  try {
    const softwareList = await Software.getAllSoftware();
    res.status(200).json(softwareList);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 获取单个软件详情
exports.getSoftwareById = async (req, res) => {
  try {
    const software = await Software.getSoftwareById(req.params.id);
    if (!software) {
      return res.status(404).json({ message: '未找到该软件' });
    }
    res.status(200).json(software);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 上传新软件
exports.uploadSoftware = async (req, res) => {
  try {
    if (!req.files || !req.files.softwareFile) {
      return res.status(400).json({ message: '未上传软件文件' });
    }

    const softwareFile = req.files.softwareFile;
    const uploadFolder = process.env.UPLOAD_FOLDER || 'uploads';
    const fileName = `${Date.now()}-${softwareFile.name}`;
    const filePath = path.join(__dirname, '..', uploadFolder, fileName);

    // 确保上传目录存在
    if (!fs.existsSync(path.join(__dirname, '..', uploadFolder))) {
      fs.mkdirSync(path.join(__dirname, '..', uploadFolder), { recursive: true });
    }

    // 移动文件到上传目录
    await softwareFile.mv(filePath);

    // 创建软件记录
    const softwareData = {
      name: req.body.name,
      version: req.body.version,
      description: req.body.description,
      category: req.body.category,
      file_path: `${uploadFolder}/${fileName}`,
      file_size: softwareFile.size,
      cover_image: req.body.cover_image || null
    };

    const newSoftware = await Software.createSoftware(softwareData);
    res.status(201).json(newSoftware);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 更新软件信息
exports.updateSoftware = async (req, res) => {
  try {
    const softwareId = req.params.id;
    const softwareData = req.body;

    // 如果有新文件上传
    if (req.files && req.files.softwareFile) {
      const softwareFile = req.files.softwareFile;
      const uploadFolder = process.env.UPLOAD_FOLDER || 'uploads';
      const fileName = `${Date.now()}-${softwareFile.name}`;
      const filePath = path.join(__dirname, '..', uploadFolder, fileName);

      // 移动新文件
      await softwareFile.mv(filePath);

      // 删除旧文件
      const oldSoftware = await Software.getSoftwareById(softwareId);
      if (oldSoftware && oldSoftware.file_path) {
        const oldFilePath = path.join(__dirname, '..', oldSoftware.file_path);
        if (fs.existsSync(oldFilePath)) {
          fs.unlinkSync(oldFilePath);
        }
      }

      softwareData.file_path = `${uploadFolder}/${fileName}`;
      softwareData.file_size = softwareFile.size;
    }

    const updatedSoftware = await Software.updateSoftware(softwareId, softwareData);
    res.status(200).json(updatedSoftware);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 下载软件
exports.downloadSoftware = async (req, res) => {
  try {
    const software = await Software.getSoftwareById(req.params.id);
    if (!software) {
      return res.status(404).json({ message: '未找到该软件' });
    }

    // 增加下载计数
    await Software.incrementDownloadCount(req.params.id);

    // 获取文件路径
    const filePath = path.join(__dirname, '..', software.file_path);

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({ message: '软件文件不存在' });
    }

    // 设置响应头，触发下载
    res.setHeader('Content-Disposition', `attachment; filename="${path.basename(filePath)}"`);
    res.setHeader('Content-Type', 'application/octet-stream');

    // 创建文件流并管道到响应
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 删除软件
exports.deleteSoftware = async (req, res) => {
  try {
    const softwareId = req.params.id;
    const software = await Software.getSoftwareById(softwareId);

    if (!software) {
      return res.status(404).json({ message: '未找到该软件' });
    }

    // 删除服务器上的文件
    const filePath = path.join(__dirname, '..', software.file_path);
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }

    // 从数据库中删除记录
    await Software.deleteSoftware(softwareId);

    res.status(200).json({ message: '软件删除成功' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};